package com.wuhao.springboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wuhao.springboot.common.Constants;
import com.wuhao.springboot.entity.Role;
import com.wuhao.springboot.entity.dto.UserDTO;
import com.wuhao.springboot.entity.User;
import com.wuhao.springboot.entity.ro.EditRoleRO;
import com.wuhao.springboot.entity.ro.PageRO;
import com.wuhao.springboot.entity.vo.TokenInfoVO;
import com.wuhao.springboot.exception.ServiceException;
import com.wuhao.springboot.mapper.RoleMapper;
import com.wuhao.springboot.mapper.UserMapper;
import com.wuhao.springboot.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuhao.springboot.utils.TokenUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 吴昊
 * @since 2022-12-12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private static final Log LOG = Log.get();

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;

    @Override
    public UserDTO login(UserDTO userDTO) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("username", userDTO.getUsername());
        User user = this.getOne(qw);
        if (Objects.isNull(user)) {
            throw new ServiceException(HttpStatus.OK.toString(), "用户不存在");
        }
        if (!StringUtils.equals(user.getPassword(), userDTO.getPassword())) {
            throw new ServiceException(HttpStatus.OK.toString(), "密码错误");
        }
        User one = getUserInfo(userDTO);
        TokenInfoVO tokenInfo = new TokenInfoVO();
        tokenInfo.setUserId(one.getId());
        String token = TokenUtils.getToken(tokenInfo);
        userDTO.setToken(token);
        Optional.ofNullable(roleMapper.selectById(one.getRoleId())).ifPresent(
                role -> {
                    userDTO.setRoleName(role.getName());
                }
        );

        return userDTO;
    }

    @Override
    public User register(UserDTO userDTO) {
        User one = getUserInfo(userDTO);
        QueryWrapper<Role> roleQueryWrapper=new QueryWrapper<>();
        roleQueryWrapper.eq("name","客户");
        if (one == null) {
            one = new User();
            BeanUtil.copyProperties(userDTO, one, true);
            Role role= roleMapper.selectList(roleQueryWrapper).get(0);
            one.setRoleId(role.getId());
            save(one);
        } else {
            throw new ServiceException(Constants.CODE_600, "用户已存在");
        }

        return one;
    }

    @Override
    public Page<UserDTO> pageUser(PageRO ro) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        User currentUser = TokenUtils.getCurrentUser();
        wrapper.ne("id", currentUser.getId());
        Page<User> page = this.page(new Page<>(ro.getCurrent(), ro.getSize()), wrapper);
        List<UserDTO> userDTOS = Lists.newArrayList();
        page.getRecords().forEach(user -> {
            UserDTO dto = new UserDTO();
            try {
                BeanUtils.copyProperties(dto, user);
                Optional.ofNullable(roleMapper.selectById(user.getRoleId())).ifPresent(
                        role -> {
                            dto.setRoleName(role.getName());
                        }
                );
                userDTOS.add(dto);
            } catch (IllegalAccessException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        });
        Page<UserDTO> userDTOPage = new Page<>();
        userDTOPage.setRecords(userDTOS);
        userDTOPage.setPages(page.getPages());
        userDTOPage.setTotal(page.getTotal());
        return userDTOPage;
    }

    @Override
    public void editRole(EditRoleRO ro) {
        User user = userMapper.selectById(ro.getUserId());
        user.setRoleId(ro.getRoleId());
        userMapper.updateById(user);
    }

    private User getUserInfo(UserDTO userDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDTO.getUsername());
        queryWrapper.eq("password", userDTO.getPassword());
        User one;
        try {
            one = getOne(queryWrapper);//从数据库查询用户信息
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }
        return one;
    }


}